//
//  MYStatusViewModel.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/25.
//  Copyright © 2016年 lianglong. All rights reserved.

/* 处理微博模型提供的数据不能被直接使用的部分 */

import UIKit

class MYStatusViewModel: NSObject {
    
    var status: MYStatus?
    
    ///头像的URL
    var headIconURL: NSURL?
    //认证
    var verifiedImage: UIImage?
    //等级
    var mbrankImage: UIImage?
    //转发数
    var repostTitle: String?
    //评论数
    var commentTitle: String?
    //点赞数
    var likeTitle: String?
    //微博来源
    var souseText: String?
    //微博发布时间
    var time: String? {
        return NSDate.sinaDate(status?.created_at ?? "")?.fullDescription()
    }
    
    
    //构造方法
    init(status: MYStatus) {
        super.init()
        
        //给微博属性赋值
        self.status = status
        
        //处理数据
        headIconURL = NSURL(string: status.user?.profile_image_url ?? "")
        dealverifiedImage()
        dealmbrankImage()
        dealSouseText()
        repostTitle = dealToolBarText(status.reposts_count, defaultText: "转发")
        commentTitle = dealToolBarText(status.comments_count, defaultText: "评论")
        likeTitle = dealToolBarText(status.attitudes_count, defaultText: "赞")
        
    }
    

}



//处理数据
extension MYStatusViewModel {
    
    //处理认证
    private func dealverifiedImage() {
        let verifiedType = status?.user?.verified ?? 0
        if verifiedType == 1 {
            verifiedImage = UIImage(named: "avatar_vip")
        }
    }
    
    //处理等级
    private func dealmbrankImage() {
        
        //设置微博等级图标
        
        let mbrank = status?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(status?.user?.mbrank)")
        }
    }
    
    
    //处理Toolbar数据
    private func dealToolBarText(count: Int, defaultText: String) -> String {
        
        if count <= 0 {
            return defaultText
        }
        
        if count >= 10000 {
            let text = Double(count / 1000) / 10
            return "\(text)万"
        }
        return "\(count)"
    }
    
    
    //处理微博来源
    private func dealSouseText() {
        //<a href=\"http://app.weibo.com/t/feed/1tqBja\" rel=\"nofollow\">360安全浏览器</a>
        
        let startFlag = "\">"
        let endFlag = "</a>"
        
        let str = status?.source ?? ""
        let startRange = str.rangeOfString(startFlag)
        let endRange = str.rangeOfString(endFlag)
        
        if let start = startRange, end = endRange {
            
            let range = start.endIndex..<end.startIndex
            souseText = str.substringWithRange(range)
        }
        
    }

}
